package com.jn.news.ui;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.jn.news.R;
import com.jn.news.utils.Constant;
import com.jn.news.utils.DatabaseHelper;
import com.jn.news.utils.SPUtils;
import com.jn.news.utils.StatusBarUtils;
import com.jn.news.utils.ToastUtil;


public class MainActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {

    private EditText etUserName;//用户名
    private EditText etPwd;  //密码
    private CheckBox cbRememberPwd;   //是否记住密码
    private CheckBox cbAutoLogin;    //是否自动登录
    private SQLiteDatabase db;
    private TextView tvLogin;
    private TextView tvToRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StatusBarUtils.with(this).init3(2, 102);

        setContentView(R.layout.activity_main);
        ToastUtil.showToast(this, "欢迎来到新闻APP");
        initView();
        initDB();
    }
    private void initView(){
        Log.e("------", "initView: ------" );
        tvLogin = findViewById(R.id.tv_login);
        etUserName = findViewById(R.id.et_username);
        etPwd = findViewById(R.id.et_pwd);
        cbRememberPwd = findViewById(R.id.cb_remember_pwd);
        cbAutoLogin = findViewById(R.id.cb_auto_login);
        tvToRegister = findViewById(R.id.tv_to_register);
        //注册点击事件
        tvLogin.setOnClickListener(this);
        tvToRegister.setOnClickListener(this);
        cbRememberPwd.setOnCheckedChangeListener(this);
        cbAutoLogin.setOnCheckedChangeListener(this);
    }

    /**
     * 初始化数据库相关
     */
    private void initDB(){
        SQLiteOpenHelper dbHelper = new DatabaseHelper(this);
        // 调用getReadableDatabase()或getWritableDatabase()才算真正创建或打开数据库
        db = dbHelper.getReadableDatabase();

    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.tv_to_register){
            //跳转到注册页面

            startActivity(new Intent(this, RegisterActivity.class));
        }
        if(v.getId() == R.id.tv_login){
            //非空校验
            if(TextUtils.isEmpty(etUserName.getText().toString().trim())){
                ToastUtil.showToast(this,"用户名不能为空");
                return;
            }
            //非空校验
            if(TextUtils.isEmpty(etPwd.getText().toString().trim())){
                ToastUtil.showToast(this,"密码不能为空");
                return;
            }
            toLogin();
        }
    }

    /**
     * 去登录
     */
    private void toLogin() {
        //1.首先判断是否记住密码和自动登录
        if(cbRememberPwd.isChecked()){
            SPUtils.put(this, Constant.USERNAME,etUserName.getText().toString().trim());
            SPUtils.put(this, Constant.PASSWORD,etPwd.getText().toString().trim());
        }
        if(cbAutoLogin.isChecked()){
            SPUtils.put(this, Constant.AUTO_LOGIN,true);
        }
        //根据用户名到数据库中查询密码
        String password = getUserPasswordIfExist(etUserName.getText().toString().trim());
        //如果查到了，校验密码是否正确
        if (password != null) {
            if(password.equals(etPwd.getText().toString().trim())){
                //将用户名保存在sharedpreferences中
                SPUtils.put(this,  Constant.USERNAME,etUserName.getText().toString().trim());
                startActivity(new Intent(this, HomeActivity.class));
                finish();
            }else{
                ToastUtil.showToast(this,"密码错误");
            }
        } else {
            //如果没查到，则提示用户名不存在
            Log.d("Login", "用户不存在");
            ToastUtil.showToast(this,"用户名不存在");
        }

    }

    //单选框点击监听
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if(buttonView.getId() == R.id.cb_remember_pwd){
                if(isChecked){
                    // 记住密码
                    cbRememberPwd.setBackgroundResource(R.mipmap.ic_selected);
                }else{
                    // 不记住密码
                    cbRememberPwd.setBackgroundResource(R.mipmap.ic_unselected);
                }
            }else if(buttonView.getId() == R.id.cb_auto_login){
                if(isChecked){
                    // 自动登录
                    cbAutoLogin.setBackgroundResource(R.mipmap.ic_selected);
                }else{
                    // 不自动登录
                    cbAutoLogin.setBackgroundResource(R.mipmap.ic_unselected);
                }
            }
    }


    /**
     * 查询用户名是否存在，并返回对应的密码（不存在时返回 null）
     */
    public String getUserPasswordIfExist(String name) {


        String[] columns = {"password","id"};
        String selection = "name = ?";
        String[] selectionArgs = {name};
        Cursor cursor = db.query(
                "user",
                columns,
                selection,
                selectionArgs,
                null,
                null,
                null
        );

        String password = null;
        if (cursor != null && cursor.moveToFirst()) {
            int index = cursor.getColumnIndex("password");
            if (index != -1) {
                password = cursor.getString(index);
            }
            int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
            SPUtils.put(this, Constant.USERID, id);
            cursor.close();
        }

        return password;
    }
}